# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
    QStyledItemDelegate,
    QSizePolicy
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
import json
import subprocess
import copy
from gui.controls import envs    
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModelMutliParams
from ..params_table import ParamsTable
from ..custom_widget import SelectBox, LineEditInt, MultRadioBtnGroup
        

class DlgBundleConnection(DlgModelMutliParams):
    materialLibraryLocking_update_signal = Signal(object)
    bundleConnection_save_signal = Signal(object)
    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("主捆绑")
        self.resize(510, 550)
        
        
        info = params.get("info") or {}
        self.connectType = info.get("connectType") or ""
        self.connects = info.get("connects") or {}

        self.materialOptions = self.getMaterialOption()

        layoutWrap = QHBoxLayout()
        layout = QVBoxLayout()
        layoutWrap.addStretch(1)
        layoutWrap.addLayout(layout)
        layoutWrap.addStretch(1)
        self.widgetDict = {}
        
        gridLayout = QGridLayout()
        self.section1GroupBox = QGroupBox(self.connects[0].get('title'))
        section1Layout = QVBoxLayout()
        self.section1GroupBox.setLayout(section1Layout)
        self.widgetDict['section1'] = SelectBox(options=[{"title":"点","value":"点"},{"title":"蒙皮桁条","value":"蒙皮桁条"}],onChanged = lambda *args, **kwargs: self.section1Changed(
                        self, *args, **kwargs
                    ),)
        
        self.widgetDict['section1Value'] = SelectBox(options=[])
        self.widgetDict['section1'].setMinimumWidth(100)
        self.widgetDict['section1Value'].setMinimumWidth(100)
        self.widgetDict['section1'].setMaximumWidth(150)
        self.widgetDict['section1Value'].setMaximumWidth(150)
        section1Layout.addWidget(self.widgetDict['section1'])
        section1Layout.addWidget(self.widgetDict['section1Value'])
        
        coordinates1GroupBox = QGroupBox('支座点坐标')
        coordinates1Layout = QVBoxLayout()
        self.widgetDict['coordinates1Table'] = ParamsTable(rows=0, columns=2)
        self.widgetDict['coordinates1Table'].setHorizontalHeaderLabels(
            [
                "轴向坐标",
                "径向坐标",
            ]
        )
        self.widgetDict['coordinates1Table'].rowSetFloat([0,1])
        coordinates1Layout.addWidget(self.widgetDict['coordinates1Table'])
        coordinates1GroupBox.setLayout(coordinates1Layout)
        section1Layout.addWidget(coordinates1GroupBox)
        
        self.scope1GroupBox = QGroupBox('支座范围')
        self.scope1GroupBox.setVisible(False) 
        scope1Layout = QVBoxLayout()
        self.widgetDict['scope1Table'] = ParamsTable(rows=0, columns=3)
        self.widgetDict['scope1Table'].setHorizontalHeaderLabels(
            [
                "轴向起",
                "径向止",
                "角度",
            ]
        )
        self.widgetDict['scope1Table'].rowSetFloat([0,1,2])
        scope1Layout.addWidget(self.widgetDict['scope1Table'])
        self.scope1GroupBox.setLayout(scope1Layout)
        section1Layout.addWidget(self.scope1GroupBox)
        # section1Layout.addStretch(1)
        
        self.section2GroupBox = QGroupBox(self.connects[1].get('title'))
        section2Layout = QVBoxLayout()
        self.section2GroupBox.setLayout(section2Layout)
        self.widgetDict['section2'] = SelectBox(options=[],onChanged = lambda *args, **kwargs: self.section2Changed(
                        self, *args, **kwargs
                    ),)
        self.widgetDict['section2Value'] = SelectBox(options=[])
        self.widgetDict['section2'].setMinimumWidth(100)
        self.widgetDict['section2Value'].setMinimumWidth(100)
        self.widgetDict['section2'].setMaximumWidth(150)
        self.widgetDict['section2Value'].setMaximumWidth(150)
        section2Layout.addWidget(self.widgetDict['section2'])
        section2Layout.addWidget(self.widgetDict['section2Value'])
        
        coordinates2GroupBox = QGroupBox('支座点坐标')
        coordinates2Layout = QVBoxLayout()
        self.widgetDict['coordinates2Table'] = ParamsTable(rows=0, columns=2)
        self.widgetDict['coordinates2Table'].setHorizontalHeaderLabels(
            [
                "轴向坐标",
                "径向坐标",
            ]
        )
        self.widgetDict['coordinates2Table'].rowSetFloat([0,1])
        coordinates2Layout.addWidget(self.widgetDict['coordinates2Table'])
        coordinates2GroupBox.setLayout(coordinates2Layout)
        section2Layout.addWidget(coordinates2GroupBox)
        
        self.scope2GroupBox = QGroupBox('支座范围')
        self.scope2GroupBox.setVisible(False) 
        scope2Layout = QVBoxLayout()
        self.widgetDict['scope2Table'] = ParamsTable(rows=0, columns=4)
        self.widgetDict['scope2Table'].setHorizontalHeaderLabels(
            [
                "轴向起",
                "径向止",
                "角度1",
                "角度2",
            ]
        )
        self.widgetDict['scope2Table'].rowSetFloat([0,1,2,3])
        scope2Layout.addWidget(self.widgetDict['scope2Table'])
        self.scope2GroupBox.setLayout(scope2Layout)
        section2Layout.addWidget(self.scope2GroupBox)
        
        icon = envs.qicons.qicon_add()
        addImg = QLabel()
        addImg.setAlignment(Qt.AlignCenter)
        pixmap = icon.pixmap(20,20)
        addImg.setPixmap(pixmap)

        
        gridLayout.addWidget(self.section1GroupBox, 0, 0)
        gridLayout.addWidget(addImg, 0, 1)
        gridLayout.addWidget(self.section2GroupBox, 0, 2)
        
        sectionLayout = QHBoxLayout()
        sectionLayout.addLayout(gridLayout)

        self.connectionIdWidget = self.createContentNumWidget()
        connectionIdLayout = QHBoxLayout()
        layout.addLayout(connectionIdLayout)
        connectionIdLayout.addWidget(self.connectionIdWidget)
        connectionIdLayout.addStretch(1)
        
        layout.addLayout(sectionLayout)
        
        mainGroupBox = QGroupBox('主捆绑')
        mainLayout = QVBoxLayout()
        
        pointGroupBox = QGroupBox('捆绑点')
        pointLayout = QVBoxLayout()
        self.widgetDict['pointTable'] = ParamsTable(rows=0, columns=3)
        self.widgetDict['pointTable'].setHorizontalHeaderLabels(
            [
                "轴向坐标",
                "径向坐标",
                "连接自由度",
            ]
        )
        self.widgetDict['pointTable'].rowSetFloat([0,1])
        self.widgetDict['pointTable'].rowSetInt([2])
        pointLayout.addWidget(self.widgetDict['pointTable'])
        pointGroupBox.setLayout(pointLayout)
        
        boltGroupBox = QGroupBox('捆绑螺栓')
        boltLayout = QVBoxLayout()
        self.widgetDict['boltTable'] = ParamsTable(rows=0, columns=3)
        self.widgetDict['boltTable'].setHorizontalHeaderLabels(
            [
                "外径",
                "内径",
                "材料",
            ]
        )
        self.widgetDict['boltTable'].rowSetFloat([0,1])
        self.widgetDict["boltTable"].rowSetSelect([2], options={"2": self.materialOptions})
        boltLayout.addWidget(self.widgetDict['boltTable'])
        boltGroupBox.setLayout(boltLayout)
        mainLayout.addWidget(pointGroupBox)
        mainLayout.addWidget(boltGroupBox)
        
        mainGroupBox.setLayout(mainLayout)
        
        layout.addWidget(mainGroupBox)
        
        layout.addStretch(1)

        btnLayout = QHBoxLayout()
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)
        
        self.setLayout(layoutWrap)
        
        if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
            self.setStageOptions(data=(self.connects[0].get("data") or {}), select=self.widgetDict["section1"])
            self.setStageOptions(data=(self.connects[1].get("data") or {}), select=self.widgetDict["section2"])
        
        data = {}
        if Config.isLocation:
            self.cacheFile = Config.cachePath + 'bundleConnection.json'
            data = Utils.read_json(self.cacheFile)
        else:
            data = params.get('data')or {}
        self.updateUI(data)
        self.lastMaterials = Utils.getTableLibrarysName(data=data.get("boltTable"), column=2)
        
        envs.ipimas_changeMaterial = lambda library, *args, **kwargs: self.libraryChange(library, *args, **kwargs)

    def initData(self, params={}):
        info = params.get("info") or {}
        self.connectType = info.get("connectType") or ""
        self.connects = info.get("connects") or {}
        self.section1GroupBox.setTitle(self.connects[0].get("title"))
        self.section2GroupBox.setTitle(self.connects[1].get("title"))
        self.widgetDict["section1"].updateItem([{"title":"点","value":"点"},{"title":"蒙皮桁条","value":"蒙皮桁条"}])
        
        for _,widget in self.widgetDict.items():
            if isinstance(widget, QTableWidget):
                widget.setRowCount(0)
            else:
                widget.setValue("")

        if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
            self.setStageOptions(data=self.connects[0].get("data") or {}, select=self.widgetDict["section1"])
            self.setStageOptions(data=self.connects[1].get("data") or {}, select=self.widgetDict["section2"])

        self.updateUI(params.get("data") or {})

    def libraryChange(self, library):
        if self.isVisible():
            self.materialData = library
        
    
    # @classmethod
    # def show(cls, parent=None, params={}):
    #     data1 = Utils.read_json(Config.cachePath + "beamAndMassPoint.json")
    #     data2 = Utils.read_json(Config.cachePath + "skeletalStructure.json")
    #     data3 = Utils.read_json(Config.cachePath + "stringer.json")
    #     params = {
    #         "data": {},
    #         "info": {
    #             "connectType": "Stage",
    #             "connects": [
    #                 {
    #                     "title": "Stage3",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": {"data":data1}},
    #                             # {"type": "杆系建模", "data": data2},
    #                             # {"type": "蒙皮桁条建模", "data": data3},
    #                         ]
    #                     },
    #                 },
    #                 {
    #                     "title": "Stage4",
    #                     "data": {
    #                         "sections": [
    #                             {"type": "梁与质量点建模", "data": {"data":data1}},
    #                             {"type": "蒙皮桁条建模", "data": {"data":data3}},
    #                         ]
    #                     },
    #                 },
    #             ],
    #         },
    #     }
        # params = {
        #     "data": {},
        #     "info": {
        #         "connectType": "Section",
        #         "connects": [
        #             {
        #                 "title": "Section4",
        #                 "type": "杆系建模",
        #                 "data": data2,
        #             },
        #             {
        #                 "title": "Section3",
        #                 "type": "梁与质量点建模",
        #                 "data": data1,
        #             },
                    
        #         ],
        #     },
        # }
        # if cls._shown:
        #     cls._instance.activateWindow()
        #     cls._instance.raise_()
        # else:
        #     cls._shown = True
        #     cls._instance = cls(parent=parent, params=params)  # 创建新实例并传入parent
        #     cls._instance.setParent(parent)  # 设置父窗口
        #     QDialog.show(cls._instance)  # 直接调用QDialog的show方法
        #     return cls._instance
        
    def getSectionOptionData(self, type, data):
        if not data: 
            return []
        options = []
        if type == "梁与质量点建模":
            data = data.get("main") or {}
        elif type == "蒙皮桁条建模":
            data = data.get("ringFrame") or {}
        else:
            data = {}
        if data:
            for key, _ in data.items():
                options.append({"title":key,"value":key})
        return options

    def getStageOptionData(self, select, index):
        options = []
        data = {}
        if select == "点":
            # 梁与质量点建模
            ls = (self.connects[index].get("data") or {}).get("sections") or []
            for item in ls:
                if item.get("sectionType") == "梁与质量点建模":
                    itemDict = item.get("data") or {}
                    data.update(itemDict.get("main") or {})
        elif select == "蒙皮桁条":
            ls = (self.connects[index].get("data") or {}).get("sections") or []
            for item in ls:
                if item.get("sectionType") == "蒙皮桁条建模":
                    itemDict = item.get("data") or {}
                    data.update(itemDict.get("ringFrame") or {})
               
        if data:
            for key, _ in data.items():
                options.append({"title":key,"value":key})
        return options     
    
    def getMaterialOption(self):
        options = []
        self.materialData = Utils.read_json(Config.cachePath + 'materialLibrary.json') or {}
        if self.materialData:
            for key, _ in self.materialData.items():
                options.append({"title":key,"value":key})
        return options
    
    def createContentNumWidget(self):
        connectionIdWidget = QWidget()
        connectionIdWidget.setFixedWidth(240)
        connectionIdLayout = QGridLayout()
        label1 = QLabel("连接编号")
        self.widgetDict["connectionId"] = LineEditInt()
        self.widgetDict["connectionId"].setClearButtonEnabled(False)
        self.widgetDict["connectionId"].setValue(123456)
        connectionIdLayout.addWidget(label1,0,0)
        connectionIdLayout.addWidget(self.widgetDict["connectionId"],0,1)

        label2 = QLabel("id")
        self.widgetDict["id"] = LineEditInt()
        self.widgetDict["id"].setClearButtonEnabled(False)
        connectionIdLayout.addWidget(label2,1,0)
        connectionIdLayout.addWidget(self.widgetDict["id"],1,1)
        connectionIdWidget.setLayout(connectionIdLayout)

        return connectionIdWidget

    def createSurfaceWidget(self):
        surfaceGroupBox = QGroupBox("Group")
        surfaceLayout = QVBoxLayout()
        
        self.widgetDict['allAround'] = MultRadioBtnGroup(options=[{"title":"周向全选","value":"周向全选"}])
        surfaceLayout.addWidget(self.widgetDict['allAround'])
        self.widgetDict['surfaceTable'] = ParamsTable(rows=0, columns=2)
        self.widgetDict['surfaceTable'].setHorizontalHeaderLabels(
            [
                "约束角度",
                "约束范围",
            ]
        )
        self.widgetDict['surfaceTable'].rowSetFloat([0,1])
        surfaceLayout.addWidget(self.widgetDict['surfaceTable'])
        surfaceGroupBox.setLayout(surfaceLayout)
        return surfaceGroupBox
        
    def createFreeWidget(self):
        self.widgetDict['freeTable'] = ParamsTable(rows=0, columns=2)
        self.widgetDict['freeTable'].setHorizontalHeaderLabels(
            [
                "主节点",
                "从节点",
            ]
        )
        self.widgetDict['freeTable'].rowSetInt([0])
        return self.widgetDict['freeTable']
                  
    def on_okBtn_clicked(self):
        dict = {}
        for key, widget in self.widgetDict.items():
            if widget.isVisible():
                if isinstance(widget, QTableWidget):
                   dict[key] =  widget.getTableData()
                # elif key == "section1Value" or key == "section2Value":
                #     dict[key] = Utils.toIntOrNone(widget.getValue())
                else:
                    dict[key] = widget.getValue()
        if Config.isLocation:
            Utils.write_json(self.cacheFile, dict)
        bolt = self.widgetDict['boltTable'].getTableData()
        self.close()
        if Config.useLibraryLocking:
            unique_library = Utils.updateLockingLibrary(dataList=[[bolt,2]], lastSelects=self.lastMaterials, library=self.materialData, file=Config.materialTable)
            if unique_library:
                if hasattr(envs, 'ipimas_changeLockMaterial'):
                    envs.ipimas_changeLockMaterial()
                self.materialLibraryLocking_update_signal.emit(unique_library)
        self.bundleConnection_save_signal.emit(dict)
        

         
    def section1Changed(self, *args):
        if args[1] == "点":
            if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
                
                self.setStageOptions(
                    data=self.connects[1].get("data") or {}, select=self.widgetDict["section2"], previous="点")
                options = self.getStageOptionData("点", 0)
                self.widgetDict["section1Value"].updateItem(options)
            self.widgetDict["section1Value"].setVisible(True)
            self.widgetDict["section2Value"].setVisible(True)
        if args[1] == "蒙皮桁条":
            if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
                self.setStageOptions(
                    data=self.connects[1].get("data") or {}, select=self.widgetDict["section2"], previous="蒙皮桁条")
                options = self.getStageOptionData("蒙皮桁条", 0)
                self.widgetDict["section1Value"].updateItem(options)
            self.widgetDict["section1Value"].setVisible(True)
            self.widgetDict["section2Value"].setVisible(True)
        
        self.showTable()
    
    def section2Changed(self, *args):
        if self.connectType == "Stage" or self.connectType == "Booster" or self.connectType == "Fairing":
            if args[1] == "点":
                    options = self.getStageOptionData("点", 1)
                    self.widgetDict["section2Value"].updateItem(options)
            if args[1] == "蒙皮桁条":
                    options = self.getStageOptionData("蒙皮桁条", 1)
                    self.widgetDict["section2Value"].updateItem(options)
        self.showTable()   

    def showTable(self):
        if self.widgetDict['section1'].getValue() == "点":
            self.scope1GroupBox.setVisible(False)
        elif self.widgetDict['section1'].getValue() == "蒙皮桁条":
            self.scope1GroupBox.setVisible(True)
        else:
            self.scope1GroupBox.setVisible(False)
         
        if self.widgetDict['section2'].getValue() == "点":
            self.scope2GroupBox.setVisible(False)
        elif self.widgetDict['section2'].getValue() == "蒙皮桁条":
            self.scope2GroupBox.setVisible(True) 
        else:
            self.scope2GroupBox.setVisible(False)      

    
    def setSectionOptions(self, flagList, select, previous=""):
        if "梁与质量点建模" in flagList:
            if previous == "点":
                select.updateItem([{"title": "点", "value": "点"}])
            elif previous == "":
                select.updateItem([])
            else:
                select.updateItem(
                    [{"title": "点", "value": "点"}]
                )
        elif "蒙皮桁条建模" in flagList :
            if previous == "点":
                select.updateItem([{"title": "蒙皮桁条", "value": "蒙皮桁条"}])
            elif previous == "蒙皮桁条":
                select.updateItem([{"title": "蒙皮桁条", "value": "蒙皮桁条"}])
            else:
                select.updateItem(
                    [{"title": "蒙皮桁条", "value": "蒙皮桁条"}]
                )
        else:
            select.updateItem([])
                
    def setStageOptions(self, data, select, previous=""):
        if not data:
            return
        options = []
        sections = data.get("sections")
        if not sections:
            return
        for item in sections:
            if item.get('sectionType') == "梁与质量点建模" :
                if previous == "点" or previous == "":
                    if {"title": "点", "value": "点"} not in options:
                        options.append({"title": "点", "value": "点"})
            elif item.get('sectionType') == "蒙皮桁条建模":
                if previous == "点" or previous == "蒙皮桁条" or previous == "":
                    if {"title": "蒙皮桁条", "value": "蒙皮桁条"} not in options:
                        options.append({"title": "蒙皮桁条", "value": "蒙皮桁条"})
        select.updateItem(options)
        
    def updateUI(self, data):
        if data:
            for widget, value in data.items():
                if widget in self.widgetDict:
                    if isinstance(self.widgetDict[widget], QTableWidget):
                        for rowData in value:
                            self.widgetDict[widget].addRow(rowData=rowData)
                    elif isinstance(self.widgetDict[widget], SelectBox):
                        self.widgetDict[widget].setValue(str(value))
                    else:
                        self.widgetDict[widget].setValue(value)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = BundleConnectionDialog()
#     window.show()
#     sys.exit(app.exec_())
